package com.ifast.leave.controller;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.hutool.core.codec.Base64;
import net.coobird.thumbnailator.Thumbnails;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.FormService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ifast.common.base.BaseController;
import com.ifast.common.utils.Result;
import com.ifast.common.utils.ShiroUtils;
import com.ifast.leave.domain.HistoryProcess;
import com.ifast.leave.domain.LeaveApply;
import com.ifast.leave.domain.LeaveTask;
import com.ifast.leave.domain.Process;
import com.ifast.leave.domain.RunningProcess;
import com.ifast.leave.service.LeaveService;
import com.ifast.sys.domain.RoleDO;
import com.ifast.sys.service.UserService;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value = "请假流程接口")
@Controller
@RequestMapping("/activiti")
public class LeaveController extends BaseController {
	@Autowired
	RepositoryService rep;
	@Autowired
	RuntimeService runservice;
	@Autowired
	FormService formservice;
	@Autowired
	IdentityService identityservice;
	@Autowired
	LeaveService leaveservice;
	@Autowired
	TaskService taskservice;
	@Autowired
	HistoryService histiryservice;
	@Autowired
	UserService sysUserService;
 
	@RequestMapping(value = "/processlist", method = RequestMethod.GET)
	String process() {
		return "leave/process_list";
	}

	@RequestMapping(value = "/uploadworkflow", method = RequestMethod.POST)
	@ResponseBody
	public Result<?> fileupload(HttpServletRequest request) {
		try {
			MultipartHttpServletRequest uploadfile = (MultipartHttpServletRequest)request;
			MultipartFile file = uploadfile.getFile("uploadfile");
			String filename = file.getOriginalFilename();
			InputStream is = file.getInputStream();
			rep.createDeployment().addInputStream(filename, is).deploy();
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail();
		}
		return Result.ok();
	}

	@RequestMapping(value = "/getprocesslists", method = RequestMethod.POST)
	@ResponseBody
	public Result<Page<Process>> getlist(Integer pageNumber, Integer pageSize) { 
		Page<Process> page = getPage(Process.class); 
		int firstrow = (page.getCurrent() - 1) * page.getSize();
		List<ProcessDefinition> list = rep.createProcessDefinitionQuery().listPage(firstrow, page.getSize());
		int total = rep.createProcessDefinitionQuery().list().size();
		List<Process> mylist = new ArrayList<Process>();
		for (int i = 0; i < list.size(); i++) {
			Process p = new Process();
			p.setDeploymentId(list.get(i).getDeploymentId());
			p.setId(list.get(i).getId());
			p.setKey(list.get(i).getKey());
			p.setName(list.get(i).getName());
			p.setResourceName(list.get(i).getResourceName());
			p.setDiagramresourcename(list.get(i).getDiagramResourceName());
			mylist.add(p);
		}  
        page.setTotal(total);
        page.setRecords(mylist); 
		return Result.ok(page);
	}

	@RequestMapping(value = "/showresource", method = RequestMethod.POST)
	@ResponseBody
	public String export(String pdid,String type,
			HttpServletResponse response) throws Exception {
		ProcessDefinition def = rep.createProcessDefinitionQuery().processDefinitionId(pdid).singleResult();
		String resource = type == "1" ? def.getResourceName() : def.getDiagramResourceName();
		try (InputStream is = rep.getResourceAsStream(def.getDeploymentId(),resource);){
			ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
			Thumbnails.of(is).scale(1).outputFormat("png").toOutputStream(stream2);
			return Base64.encode(stream2.toByteArray());
		}catch (Exception e){
			e.printStackTrace();
		}
		return "";
		/*ServletOutputStream output = response.getOutputStream();
		IOUtils.copy(is, output);*/
	}

	@RequestMapping(value = "/deletedeploy", method = RequestMethod.POST)
	@ResponseBody
	public Result<?> deletedeploy(String deployid) throws Exception {
		rep.deleteDeployment(deployid, true);
		return Result.ok();
	}

	@RequestMapping(value = "/runningprocess", method = RequestMethod.GET)
	public String task() {
		return "leave/runningprocess_list";
	}
	
	@RequestMapping(value = "getrunningprocesslists", method = RequestMethod.POST) // 参与的正在运行的请假流程
	@ResponseBody
	public Result<Page<RunningProcess>> runningprocesslists(Integer pageNumber, Integer pageSize) { 
		Page<Process> page = getPage(Process.class); 
		int firstrow = (page.getCurrent() - 1) * page.getSize();
		
		ProcessInstanceQuery query = runservice.createProcessInstanceQuery();
		int total = (int) query.count();
		List<ProcessInstance> a = query.listPage(firstrow, page.getSize());
		List<RunningProcess> list = new ArrayList<RunningProcess>();
		for (ProcessInstance p : a) {
			RunningProcess process = new RunningProcess();
			process.setActivityid(p.getActivityId());
			process.setBusinesskey(p.getBusinessKey());
			process.setExecutionid(p.getId());
			process.setProcessInstanceid(p.getProcessInstanceId());
			list.add(process);
		}
		Page<RunningProcess> grid = new Page<RunningProcess>(); 
		grid.setTotal(total);
		grid.setRecords(list);
		return Result.ok(grid);
	} 
	
	@RequestMapping(value = "/deptleaderaudit", method = RequestMethod.GET)
	public String mytask() {
		return "leave/deptleaderaudit";
	}
	@ApiOperation("获取部门领导审批代办列表")
	@RequestMapping(value = "/depttasklist", produces = {"application/json;charset=UTF-8" }, method = RequestMethod.POST)
	@ResponseBody
	public Result<Page<LeaveTask>> getdepttasklist(Integer pageNumber, Integer pageSize) { 
		Page<LeaveTask> page = getPage(LeaveTask.class); 
		int firstrow = (page.getCurrent() - 1) * page.getSize();
		Page<LeaveTask> grid = new Page<>(); 
		grid.setTotal(0);
		grid.setRecords(new ArrayList<LeaveTask>());  
		// 先做权限检查，对于没有人事权限的用户,直接返回空
		RoleDO role = new RoleDO();
		//用户权限
		Set<String> rolesId = sysUserService.listRoles(ShiroUtils.getUserId());
		//是否是  
		role = role.selectOne(new EntityWrapper<>().eq("remark", "ONE_LVL_ADMIN"));
		if((rolesId == null || !rolesId.contains(role.getId()))&& !"admin".equalsIgnoreCase(ShiroUtils.getSysUser().getUsername())){
			return Result.ok(grid);
		}   
		List<LeaveApply> results = leaveservice.getpagedepttask(ShiroUtils.getUserId().toString(), firstrow, page.getSize());
		int totalsize = leaveservice.getalldepttask(ShiroUtils.getUserId().toString());
		List<LeaveTask> tasks = new ArrayList<LeaveTask>();
		results.removeAll(Collections.singleton(null)); 
		for (LeaveApply apply : results) {
			LeaveTask task = new LeaveTask();
			task.setApply_time(apply.getApplyTime());
			task.setUser_id(apply.getUserId());
			task.setEnd_time(apply.getEndTime());
			task.setId(apply.getId());
			task.setLeave_type(apply.getLeaveType());
			task.setProcess_instance_id(apply.getProcessInstanceId());
			task.setProcessdefid(apply.getTask().getProcessDefinitionId());
			task.setReason(apply.getReason());
			task.setStart_time(apply.getStartTime());
			task.setTaskcreatetime(apply.getTask().getCreateTime());
			task.setTaskid(apply.getTask().getId());
			task.setTaskname(apply.getTask().getName());
			tasks.add(task);
		} 
		grid.setTotal(totalsize);
		grid.setRecords(tasks);
		return Result.ok(grid); 
	}
	
	@RequestMapping(value = "/hraudit", method = RequestMethod.GET)
	public String hr() {
		return "leave/hraudit";
	}
	
	@RequestMapping(value = "/hrtasklist", produces = { "application/json;charset=UTF-8" }, method = RequestMethod.POST)
	@ResponseBody
	public Result<Page<LeaveTask>> gethrtasklist(Integer pageNumber, Integer pageSize) { 
		Page<LeaveTask> page = getPage(LeaveTask.class); 
		int firstrow = (page.getCurrent() - 1) * page.getSize();
		Page<LeaveTask> grid = new Page<>(); 
		grid.setTotal(0);
		grid.setRecords(new ArrayList<LeaveTask>());  
		// 先做权限检查，对于没有人事权限的用户,直接返回空
		RoleDO role = new RoleDO();
		//用户权限
		Set<String> rolesId = sysUserService.listRoles(ShiroUtils.getUserId());
		//是否是  
		role = role.selectOne(new EntityWrapper<>().eq("remark", "TWO_LVL_ADMIN"));
		if((rolesId == null || !rolesId.contains(role.getId()))&& !"admin".equalsIgnoreCase(ShiroUtils.getSysUser().getUsername())){
			return Result.ok(grid);
		} 
			 
		List<LeaveApply> results = leaveservice.getpagehrtask(null, firstrow, grid.getSize());
		int totalsize = leaveservice.getallhrtask(null);
		List<LeaveTask> tasks = new ArrayList<LeaveTask>();
		for (LeaveApply apply : results) {
			LeaveTask task = new LeaveTask();
			task.setApply_time(apply.getApplyTime());
			task.setUser_id(apply.getUserId());
			task.setEnd_time(apply.getEndTime());
			task.setId(apply.getId());
			task.setLeave_type(apply.getLeaveType());
			task.setProcess_instance_id(apply.getProcessInstanceId());
			task.setProcessdefid(apply.getTask().getProcessDefinitionId());
			task.setReason(apply.getReason());
			task.setStart_time(apply.getStartTime());
			task.setTaskcreatetime(apply.getTask().getCreateTime());
			task.setTaskid(apply.getTask().getId());
			task.setTaskname(apply.getTask().getName());
			tasks.add(task);
		}
		 
		grid.setTotal(totalsize);
		grid.setRecords(tasks);
		return Result.ok(grid); 
	} 
	
	
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String my() {
		return "index";
	}

	@RequestMapping(value = "/leaveapply", method = RequestMethod.GET)
	public String leave() {
		return "leave/leaveapply";
	}  

	@RequestMapping(value = "/startleave", method = RequestMethod.POST)
	@ResponseBody
	public Result start_leave(LeaveApply apply, HttpSession session) throws Exception {
		String userid = ShiroUtils.getUserId().toString();
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("applyuserid", userid);
		ProcessInstance ins = leaveservice.startWorkflow(apply, userid, variables);
		System.out.println("流程id" + ins.getId() + "已启动");
		return Result.ok("sucess");
	}
 
	
	@RequestMapping(value = "/modifyapply", method = RequestMethod.GET)
	public String modifyapply() {
		return "leave/modifyapply";
	}

	@RequestMapping(value = "/updatetasklist", produces = { "application/json;charset=UTF-8" }, method = RequestMethod.POST)
	@ResponseBody
	public Result<Page<LeaveTask>> getupdatetasklist(Integer pageNumber, Integer pageSize) { 
		Page<LeaveTask> page = getPage(LeaveTask.class); 
		int firstrow = (page.getCurrent() - 1) * page.getSize();
		String userid = ShiroUtils.getUserId().toString();
		List<LeaveApply> results = leaveservice.getpageupdateapplytask(userid, firstrow, page.getSize());
		int totalsize = leaveservice.getallupdateapplytask(userid);
		List<LeaveTask> tasks = new ArrayList<LeaveTask>();
		for (LeaveApply apply : results) {
			LeaveTask task = new LeaveTask();
			task.setApply_time(apply.getApplyTime());
			task.setUser_id(apply.getUserId());
			task.setEnd_time(apply.getEndTime());
			task.setId(apply.getId());
			task.setLeave_type(apply.getLeaveType());
			task.setProcess_instance_id(apply.getProcessInstanceId());
			task.setProcessdefid(apply.getTask().getProcessDefinitionId());
			task.setReason(apply.getReason());
			task.setStart_time(apply.getStartTime());
			task.setTaskcreatetime(apply.getTask().getCreateTime());
			task.setTaskid(apply.getTask().getId());
			task.setTaskname(apply.getTask().getName());
			tasks.add(task);
		}
		Page<LeaveTask> grid = new Page<LeaveTask>(); 
		grid.setTotal(totalsize);
		grid.setRecords(tasks);
		return Result.ok(grid);
	}
	
	@RequestMapping(value = "/modifyapplytask/{taskid}", method = RequestMethod.GET) 
	public String modifyapplytask(Model model,@PathVariable("taskid") String taskid, HttpServletResponse response) {
		Task task = taskservice.createTaskQuery().taskId(taskid).singleResult();
		ProcessInstance process = runservice.createProcessInstanceQuery()
				.processInstanceId(task.getProcessInstanceId()).singleResult(); 
		LeaveApply leave = new LeaveApply().selectById(process.getBusinessKey());
		leave.setTask(task);
		model.addAttribute("leave", leave);
		return "/leave/modifyapply_task";
	} 
	
	@RequestMapping(value = "/task/updatecomplete/{taskid}", method = RequestMethod.POST)
	@ResponseBody
	public Result updatecomplete(@PathVariable("taskid") String taskid,LeaveApply leave,String reapply) {
		leaveservice.updatecomplete(taskid, leave, reapply);
		return Result.ok("success");
	}
	
	@RequestMapping(value = "/dealtask/{taskid}", method = RequestMethod.GET) 
	public String taskdeal(Model model,@PathVariable("taskid") String taskid, HttpServletResponse response) {
		Task task = taskservice.createTaskQuery().taskId(taskid).singleResult();
		ProcessInstance process = runservice.createProcessInstanceQuery()
				.processInstanceId(task.getProcessInstanceId()).singleResult(); 
		LeaveApply leave = new LeaveApply().selectById(process.getBusinessKey());
		leave.setTask(task);
		model.addAttribute("leave", leave);
		return "/leave/deal_task";
	}
	
	@RequestMapping(value = "/hrdealtask/{taskid}", method = RequestMethod.GET) 
	public String hrdealtask(Model model,@PathVariable("taskid") String taskid, HttpServletResponse response) {
		Task task = taskservice.createTaskQuery().taskId(taskid).singleResult();
		ProcessInstance process = runservice.createProcessInstanceQuery()
				.processInstanceId(task.getProcessInstanceId()).singleResult(); 
		LeaveApply leave = new LeaveApply().selectById(process.getBusinessKey());
		leave.setTask(task);
		model.addAttribute("leave", leave);
		return "/leave/hrdeal_task";
	}
	

	@RequestMapping(value = "/task-deptleaderaudit", method = RequestMethod.GET)
	String url() {
		return "/leave/task-deptleaderaudit";
	}

	@RequestMapping(value = "/task/deptcomplete/{taskid}", method = RequestMethod.POST)
	@ResponseBody
	public Result<?> deptcomplete(HttpSession session,@PathVariable("taskid") String taskid,String deptleaderapprove, HttpServletRequest req) {
		String userid = ShiroUtils.getUserId().toString();
		Map<String, Object> variables = new HashMap<String, Object>(); 
		variables.put("deptleaderapprove", deptleaderapprove);
		taskservice.claim(taskid, userid);
		taskservice.complete(taskid, variables);
		return Result.ok();
	}

	@RequestMapping(value = "/task/hrcomplete/{taskid}", method = RequestMethod.POST)
	@ResponseBody
	public Result hrcomplete(HttpSession session, @PathVariable("taskid") String taskid,String hrapprove, HttpServletRequest req) {
		String userid = ShiroUtils.getUserId().toString();
		Map<String, Object> variables = new HashMap<String, Object>(); 
		variables.put("hrapprove", hrapprove);
		taskservice.claim(taskid, userid);
		taskservice.complete(taskid, variables);
		return  Result.ok();
	}

	@RequestMapping(value = "/reportback", method = RequestMethod.GET)
	public String reprotback() {
		return "leave/reportback";
	}
	
	@RequestMapping(value = "/xjtasklist", produces = { "application/json;charset=UTF-8" }, method = RequestMethod.POST)
	@ResponseBody
	public Result<Page<LeaveTask>> getXJtasklist(Integer pageNumber, Integer pageSize) { 
		Page<LeaveTask> page = getPage(LeaveTask.class); 
		int firstrow = (page.getCurrent() - 1) * page.getSize();
		String userid = ShiroUtils.getUserId().toString();
		List<LeaveApply> results = leaveservice.getpageXJtask(userid, firstrow, page.getSize());
		int totalsize = leaveservice.getallXJtask(userid);
		List<LeaveTask> tasks = new ArrayList<LeaveTask>();
		for (LeaveApply apply : results) {
			LeaveTask task = new LeaveTask();
			task.setApply_time(apply.getApplyTime());
			task.setUser_id(apply.getUserId());
			task.setEnd_time(apply.getEndTime());
			task.setId(apply.getId());
			task.setLeave_type(apply.getLeaveType());
			task.setProcess_instance_id(apply.getProcessInstanceId());
			task.setProcessdefid(apply.getTask().getProcessDefinitionId());
			task.setReason(apply.getReason());
			task.setStart_time(apply.getStartTime());
			task.setTaskcreatetime(apply.getTask().getCreateTime());
			task.setTaskid(apply.getTask().getId());
			task.setTaskname(apply.getTask().getName());
			tasks.add(task);
		}
		Page<LeaveTask> grid = new Page<LeaveTask>(); 
		grid.setTotal(totalsize);
		grid.setRecords(tasks);
		return Result.ok(grid);
	}
	
	@RequestMapping(value = "/reportdealtask/{taskid}", method = RequestMethod.GET) 
	public String reportdealtask(Model model,@PathVariable("taskid") String taskid, HttpServletResponse response) {
		Task task = taskservice.createTaskQuery().taskId(taskid).singleResult();
		ProcessInstance process = runservice.createProcessInstanceQuery()
				.processInstanceId(task.getProcessInstanceId()).singleResult(); 
		LeaveApply leave = new LeaveApply().selectById(process.getBusinessKey());
		leave.setTask(task);
		model.addAttribute("leave", leave);
		return "/leave/report_deal_task";
	}
	
	
	@RequestMapping(value = "/task/reportcomplete/{taskid}", method = RequestMethod.POST)
	@ResponseBody
	public Result reportbackcomplete(@PathVariable("taskid") String taskid,String realstart_time,String realend_time, HttpServletRequest req) {
		leaveservice.completereportback(taskid, realstart_time, realend_time);
		return Result.ok("success");
	} 

	@RequestMapping(value = "involvedprocess", method = RequestMethod.POST) // 参与的正在运行的请假流程
	@ResponseBody
	public Result<Page<RunningProcess>> allexeution(Integer pageNumber, Integer pageSize) { 
		Page<LeaveTask> page = getPage(LeaveTask.class); 
		int firstrow = (page.getCurrent() - 1) * page.getSize();
		String userid = ShiroUtils.getUserId().toString();
		ProcessInstanceQuery query = runservice.createProcessInstanceQuery();
		int total = (int) query.count();
		List<ProcessInstance> a = query.processDefinitionKey("leave").involvedUser(userid).listPage(firstrow, page.getSize());
		List<RunningProcess> list = new ArrayList<RunningProcess>();
		for (ProcessInstance p : a) {
			RunningProcess process = new RunningProcess();
			process.setActivityid(p.getActivityId());
			process.setBusinesskey(p.getBusinessKey());
			process.setExecutionid(p.getId());
			process.setProcessInstanceid(p.getProcessInstanceId());
			list.add(process);
		}
		Page<RunningProcess> grid = new Page<RunningProcess>(); 
		grid.setTotal(total);
		grid.setRecords(list);
		return Result.ok(grid);
	}

	@RequestMapping(value = "/getfinishprocess", method = RequestMethod.POST)
	@ResponseBody
	public Result<Page<HistoryProcess>> getHistory(Integer pageNumber, Integer pageSize) { 
		Page<LeaveTask> page = getPage(LeaveTask.class); 
		int firstrow = (page.getCurrent() - 1) * page.getSize();
		String userid = ShiroUtils.getUserId().toString();
		HistoricProcessInstanceQuery process = histiryservice.createHistoricProcessInstanceQuery()
				.processDefinitionKey("leave").startedBy(userid).finished();
		int total = (int) process.count();
		 
		List<HistoricProcessInstance> info = process.listPage(firstrow, page.getSize());
		List<HistoryProcess> list = new ArrayList<HistoryProcess>();
		for (HistoricProcessInstance history : info) {
			HistoryProcess his = new HistoryProcess();
			String bussinesskey = history.getBusinessKey();
			LeaveApply apply = new LeaveApply().selectById(bussinesskey); 
			his.setLeaveapply(apply);
			his.setBusinessKey(bussinesskey);
			his.setProcessDefinitionId(history.getProcessDefinitionId());
			list.add(his);
		}
		Page<HistoryProcess> grid = new Page<HistoryProcess>(); 
		grid.setTotal(total);
		grid.setRecords(list);
		return Result.ok(grid);
	}

	@RequestMapping(value = "/historyprocess", method = RequestMethod.GET)
	public String history() {
		return "leave/historyprocess";
	}

	@RequestMapping(value = "/processinfo", method = RequestMethod.GET) 
	public String processinfo(Model model,String instanceid) { 
		model.addAttribute("instanceId", instanceid);
		return "leave/history_info_list";
	}
	
	@RequestMapping(value = "/processinfoJson", method = RequestMethod.GET)
	@ResponseBody
	public Result<Page<HistoricActivityInstance>> processinfo(String instanceid) {
		List<HistoricActivityInstance> his = histiryservice.createHistoricActivityInstanceQuery()
				.processInstanceId(instanceid).orderByHistoricActivityInstanceStartTime().asc().list(); 
		Page<HistoricActivityInstance> grid = new Page<HistoricActivityInstance>(); 
		grid.setTotal(his.size());
		grid.setRecords(his);
		return Result.ok(grid);
	}
	

	@RequestMapping(value = "/processhis", method = RequestMethod.POST)
	@ResponseBody
	public List<HistoricActivityInstance> processhis(@RequestParam("ywh") String ywh) {
		String instanceid = histiryservice.createHistoricProcessInstanceQuery().processDefinitionKey("purchase")
				.processInstanceBusinessKey(ywh).singleResult().getId();
		List<HistoricActivityInstance> his = histiryservice.createHistoricActivityInstanceQuery()
				.processInstanceId(instanceid).orderByHistoricActivityInstanceStartTime().asc().list();
		return his;
	}

	@RequestMapping(value = "myleaveprocess", method = RequestMethod.GET)
	String myleaveprocess() {
		return "leave/myleaveprocess";
	}

	@RequestMapping(value = "traceprocess/{executionid}", method = RequestMethod.GET)
	public void traceprocess(@PathVariable("executionid") String executionid, HttpServletResponse response)
			throws Exception {
		ProcessInstance process = runservice.createProcessInstanceQuery().processInstanceId(executionid).singleResult();
		BpmnModel bpmnmodel = rep.getBpmnModel(process.getProcessDefinitionId());
		List<String> activeActivityIds = runservice.getActiveActivityIds(executionid);
		DefaultProcessDiagramGenerator gen = new DefaultProcessDiagramGenerator();
		// 获得历史活动记录实体（通过启动时间正序排序，不然有的线可以绘制不出来）
		List<HistoricActivityInstance> historicActivityInstances = histiryservice.createHistoricActivityInstanceQuery()
				.executionId(executionid).orderByHistoricActivityInstanceStartTime().asc().list();
		// 计算活动线
		List<String> highLightedFlows = leaveservice
				.getHighLightedFlows(process.getProcessDefinitionId(),
						historicActivityInstances);

		InputStream in = gen.generateDiagram(bpmnmodel, "png", activeActivityIds, highLightedFlows, "宋体", "宋体", null,
				null, 1.0);
		// InputStream in=gen.generateDiagram(bpmnmodel, "png",
		// activeActivityIds);
		ServletOutputStream output = response.getOutputStream();
		IOUtils.copy(in, output);
	}

	@RequestMapping(value = "myleaves", method = RequestMethod.GET)
	String myleaves() {
		return "leave/myleaves";
	}

	@RequestMapping(value = "setupprocess", method = RequestMethod.POST)
	@ResponseBody
	public Result<Page<RunningProcess>> setupprocess(Integer pageNumber, Integer pageSize) { 
		Page<LeaveTask> page = getPage(LeaveTask.class); 
		int firstrow = (page.getCurrent() - 1) * page.getSize();
		String userid = ShiroUtils.getUserId().toString();
		System.out.print(userid);
		ProcessInstanceQuery query = runservice.createProcessInstanceQuery();
		int total = (int) query.count();
		List<ProcessInstance> a = query.processDefinitionKey("leave").involvedUser(userid).listPage(firstrow, page.getSize());
		List<RunningProcess> list = new ArrayList<RunningProcess>();
		for (ProcessInstance p : a) {
			RunningProcess process = new RunningProcess();
			process.setActivityid(p.getActivityId());
			process.setBusinesskey(p.getBusinessKey());
			process.setExecutionid(p.getId());
			process.setProcessInstanceid(p.getProcessInstanceId());
			LeaveApply l = new LeaveApply().selectById(p.getBusinessKey());
			if ("admin".equalsIgnoreCase(ShiroUtils.getSysUser().getUsername()) || userid.equals(l.getUserId()))
				list.add(process);
			else
				continue;
		}
		Page<RunningProcess> grid = new Page<RunningProcess>(); 
		grid.setTotal(total);
		grid.setRecords(list);
		return Result.ok(grid);
	}

}
